package com.market.web.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.market.domain.Location;
import com.market.domain.PickupSchedule;
import com.market.domain.transients.DAY_OF_WEEK;
import com.market.manager.LocationManager;
import com.market.util.CollectionUtil;
import com.market.web.model.LocationModel;
import com.market.web.model.MarketList;
import com.market.web.model.domain.PickupInfo;

@Controller("locationController")
@Scope("session")
public class LocationController extends
		GenericController<LocationManager, LocationModel, Location> {

	@Override
	@Autowired
	protected void setModel(LocationModel model) {
		this.model = model;

	}

	@Override
	@Autowired
	protected void setManager(LocationManager manager) {
		this.manager = manager;
	}

	/**
	 * This method have to extract pick days information
	 */
	@Override
	public Location saveCurrent() {
		// CollectionUtil<PickupSchedule> util = new
		// CollectionUtil<PickupSchedule>();
		// List<PickupSchedule> curPickupDays =
		// util.extractSelected(this.model.getAllPickupSchedules());
		// this.getModelCurrent().setPickupSchedules(curPickupDays);
		Boolean isExist = Boolean.FALSE;
		for (DAY_OF_WEEK day : DAY_OF_WEEK.values()) {
			isExist = Boolean.FALSE;
			for (PickupSchedule schedule : this.getModelCurrent()
					.getPickupSchedules()) {
				if (schedule.getDayOfWeek().equals(day)) {
					isExist = Boolean.TRUE;
					break;
				}
			}
			if (isExist == Boolean.FALSE) {
				PickupSchedule schedule = new PickupSchedule();
				schedule.setDayOfWeek(day);
				schedule.setIsNew(true);
				this.getModelCurrent().getPickupSchedules().add(schedule);
			}
		}

		return super.saveCurrent();
	}

	public List<PickupInfo> getPickupInfo() {
		this.init();
		List<PickupInfo> locs = new ArrayList<PickupInfo>();
		for (Location loc : this.getModel().getList()) {
			locs.add(new PickupInfo(this.manager.fetchOne(loc)));
		}
		return locs;
	}

	public List<PickupInfo> getValidPickupInfo() {
		this.init();
		List<PickupInfo> locs = new ArrayList<PickupInfo>();
		for (Location loc : this.getModel().getList()) {
			if (!loc.getIsCanceled()) {
				locs.add(new PickupInfo(this.manager.fetchOne(loc)));
			}
		}
		return locs;
	}

	public void initOrderByNumber() {
		List<Location> all = manager.fetchAllOrderByNumber();
		if (all.size() > 0) {
			model.setList(all);
			this.refreshCurrent();
		}
		this.model.setIsInitialized(true);
	}

}
